const RDBCModel = require("@/model/RDBC");
const { Op } = require("sequelize");
const z_base = require("./z_base");

const role = {
  /**
   * 根据 [userInfoId] 获取 [角色标签列表]
   * @param {*} userInfoID
   * @returns [label]
   */
  async GetLabelsByUserInfoId(userInfoID) {
    try {
      //结构数组中的第一个元素
      let [rows] = await global.mysqlPool.execute(
        `select label from role r,user_role ur where r.id=ur.role_id AND ur.user_id = ?`,
        [userInfoID]
      );
      let label = rows.map((item) => item.label);
      return label;
    } catch (error) {
      console.log("查询用户角色标签列表失败", error);
    }
  },
  async GetList(params) {
    let list = [],
      total = 0;
    let whereClause = {}; //条件
    if (params?.keyword && params.keyword !== "") {
      whereClause.name = {
        [Op.like]: `%${params.keyword}%`,
      };
    }

    //使用squlize的模型统计数量
    total = await RDBCModel.Role.count({ where: whereClause });
    const result = await RDBCModel.Role.findAll({
      //查询的列属性
      attributes: ["id", "name", "label", "created_at", "is_disable"],
      where: whereClause,
      limit: +params?.page_size,
      offset: (+params.page_num - 1) * +params.page_size,
    });

    result.forEach((item) => {
      list.push(item.dataValues);
    });

    /* 
   value= {
      id: 1,
      name: '管理员',
      label: 'admin',
      created_at: 2022-10-20T21:24:28.000Z,
      is_disable: 0
    }
    */
    return {
      list,
      total,
    };
  },
  // 根据 [角色id] 查询出 [资源id列表]
  async GetResourcesByRoldId(role_id) {
    try {
      let resources = await RDBCModel.RoleResource.findAll({
        attributes: ["resource_id"],
        where: {
          role_id,
        },
      });
      resources = resources.map((resource) => {
        return resource.dataValues?.resource_id;
      });
      return resources;
    } catch (error) {
      console.log("GetResourcesByRoldId失败", error);
    }
  },
  // 根据 [角色id] 查询出 [目录id列表]
  async GetMenusByRoleId(role_id) {
    try {
      let menus = await RDBCModel.RoleMenu.findAll({
        attributes: ["menu_id"],
        where: { role_id },
      });
      menus = menus.map((resource) => {
        return resource.dataValues?.menu_id;
      });
      return menus;
    } catch (error) {
      console.log("GetMenusByRoleId失败", error);
    }
  },
  // 根据 [角色id] 获取 [角色标签列表]
  async GetLabelsByRoleIds(ids) {
    const [rows] = await global.mysqlPool.execute(
      `select label from role where id IN (${ids.join(",")})`
    );
    // [ { label: 'baoan' } ]
    return rows;
  },
};

module.exports = role;
